/**
 * 后台文章管理路由
 */
const express = require('express');

// 用户中间件
const user = require('../../middleware/user');
// 文章信息中间件
const article = require('../../middleware/article');

// 导航类目中间件
const category = require('../../middleware/category');
// 后台文章管理路由
const articleApp = express();

articleApp.use(user.lastLoginTime)
articleApp.use(category.getList);


// 文章列表页
articleApp.get('/',[article.getCountEnd],(req,res,next)=>{
    // 用户信息，文章信息
    let {articleCount} = req;
    let size = 6;
    req.page = {};
    // 文章总数
    req.page.count = articleCount;
    // 总页数
    req.page.total = Math.ceil(req.page.count/size);  
    // 当前页数
    req.page.p = req.query.p ? req.query.p : 1;
    req.page.p = req.page.p > req.page.total ? req.page.total : req.page.p;
    req.page.p = req.page.p < 1 ? 1:req.page.p;
    
    res.start = (req.page.p - 1) * size;
    res.size = size;
    next();
},[article.getPageEnd],(req,res) => {
    let {user,pageList,page,category} = req;
    page.list = pageList;
    let {category_id,hot} = req.query;
    res.render('admin/article/index',{user,page,category,category_id,hot})
});
// 设置热门路由
articleApp.get('/sethot',article.setHot,(req,res) => {
    if(req.affectedRows){
        res.json({code:1,msg:'设置热门成功'})
    }else{
        res.json({code:0,msg:'设置热门失败'})
    }
});
// 显示添加博文页
articleApp.get('/add',[],(req,res) => {
    let {user,category} = req;
    // console.log((new Date().toLocaleDateString()))
    res.render('admin/article/add',{user,category,code:''});
});
// 添加博文操作
articleApp.post('/add',article.add,(req,res) => {
    let {user,category} = req;
    if(req.insertId){
        res.render('admin/article/add',{user,category,code:1});
    }else{
        res.render('admin/article/add',{user,category,code:2});
    }
});

// ckeditor上传文件
articleApp.post('/ckeditor',(req,res) => {
    if(req.uploadUrl){
        res.json({
            uploaded:true,
            url:req.uploadUrl
        })
    }else{
        res.json({
            uploaded:false,
            err:{message:'上传失败'}
        })
    }
});

// 删除文章
articleApp.get('/del',article.del,(req,res) => {
    if(req.affectedRows){
        res.json({code:1,msg:'删除成功'})
    }else{
        res.json({code:0,msg:'删除失败'})
    }
});
// 编辑文章显示页面
articleApp.get('/edit/:id',[article.getArticleById],(req,res) => {
    let {user,category,articles} = req;
    res.render('admin/article/edit',{user,category,articles});
});
// 编辑文章页面操作
articleApp.post('/edit',[article.edit],(req,res) => {
    if(req.affectedRows > 0){
        res.render('admin/alert',{code:true,title:'成功提示',message:'文章编辑成功',url:'/admin/article/'});
    }else{
        res.render('admin/alert',{code:true,title:'失败提示',message:'文章编辑失败',url:'/admin/article/edit/'+req.body.id});
    }
});
module.exports = articleApp;